function showSuccessMsg() {
    $('.popup_con').fadeIn('fast', function() {
        setTimeout(function(){
            $('.popup_con').fadeOut('fast',function(){}); 
        },1000) 
    });
}

function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

$(document).ready(function(){
    $.get('/api/v1.0/user', function(resp){
        if (resp.errno =='4101'){
            location.href= '/login.html'
        }
        else if (resp.errno == '0'){
            $('#user-name').html(resp.data.name)
            $('#mobile').html(resp.data.mobile)
            if (resp.data.avatar){
                $('#user-avatar').attr('src', resp.data.avatar)
            }
        }
    })



    $('#form-avatar').submit(function(e){
        e.preventDefault();
        $(this).ajaxSubmit({
            url: '/api/v1.0/user/avatar',
            type: 'post',
            dataType: 'json',
            headers: {
                'X-CSRFToken': getCookie('csrf_token')
            },
            success: function(res){
                if(res.errno == '0'){
                    var avatar_url = res.data.avatar_url
                    $('#user-avatar').attr('src', avatar_url)
                }
                else{
                    alert(res.errmsg)
                }

            }

        })
    })
    $('#form-name').submit(function (e) {
        e.preventDefault()
        var name = $('#user-name').val()
        if (!name){
            alert('名字不能为空')
            return
        }
        $.ajax({
            url: '/api/v1.0/user/name',
            type: 'PUT',
            dataType: 'json',
            data: JSON.stringify({name:name}),
            contentType: 'application/json',
            headers: {
                'X-CSRFToken': getCookie('csrf_token')
            },
            success: function (res) {
                if (res.errno == '0'){
                    $('.error-msg').hide()
                    showSuccessMsg()
                }else if(res.errno=='4001') {
                    $('.error-msg').show()
                }else if (res.errno == '4101'){
                    location.href= '/login.html'
                }

            }
        })

    })


})